import {post,get} from '@/common/plugins/http'
import api from '@/common/api'
import {childrenRoutes} from "@/router"
import store from '@/store'
import {flatMap} from "lodash"

export const initUser = async () => {
    if (store.state.menu.menus.length === 0) {
        await getUserInfo()
        return await getUserMenuRouter()
    } else {
        const {childrenRoutes} = await makeRouter(store.state.menu.menus)
        return childrenRoutes
    }
}
// 获取用户信息
export const getUserInfo = async () => {
    const userInfo = await get(api.user.userInfo)
    await store.dispatch('_setCurrentUserInfo', userInfo)
}

// 获取用户菜单，并处理路由 和  数据权限
export const getUserMenuRouter = async () => {
    const menu = await get(api.systemSettings.menuManage.list)
    const {childrenRoutes, permission} = await makeRouter(menu)
    await store.dispatch('_setMenu', {menu, permission})
    return childrenRoutes
}
//判断是否包含改路由或权限
export const hasPermission = (key) => {
    return store.state.menu.permission.includes(key)
}
// 处理路由 和  数据权限
const makeRouter = async (menu) => {
    let menus = flatMap(menu, a => a.menuList)
    let menusId = []
    menus.map(item => menusId.push(item.id))
    let menusUrl = menus.filter(a => a && a.level !== 'BUTTON').map(a => a.action)
    let menuPermission = []
    flatMap(menu, a => a.menuList).forEach(a => flatMenu(a, menuPermission))
    menuPermission = menuPermission.map(a => a.action).filter(a => a)
    return {
        childrenRoutes: childrenRoutes.filter(a => menusUrl.includes(a.path) || a.meta.withoutPermission),
        permission: menuPermission,
    }
}
const flatMenu = (menu, menus) => {
    let m = {...menu}
    if (m.menuList && m.menuList.length) {
        delete m.menuList
        menus.push(m)
        menu.menuList.forEach(a => flatMenu(a, menus))
    } else {
        menus.push(m)
    }
}